package com.hh.node

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.util.Log
import android.widget.Toast
import com.qws.xprinter.flutter_xprinter.FlutterXprinterPlugin

/**
 * USB广播接收器，用于处理USB设备的连接、断开和权限请求事件
 */
class UsbReceiver : BroadcastReceiver() {
    
    // 回调接口
    interface UsbDeviceListener {
        fun onDeviceAttached(device: UsbDevice)
        fun onDeviceDetached(device: UsbDevice)
        fun onDevicePermissionGranted(device: UsbDevice)
    }
    
    // 监听器
    private var listener: UsbDeviceListener? = null
    
    // 设置监听器
    fun setUsbDeviceListener(listener: UsbDeviceListener) {
        this.listener = listener
    }
    
    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            FlutterXprinterPlugin.ACTION_USB_PERMISSION -> {
                synchronized(this) {
                    val device = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        device?.let {
                            // 已获得USB设备权限
                            Log.d("USB", "权限已授予: ${it.deviceName}")
                            Toast.makeText(context, "USB设备已授权", Toast.LENGTH_SHORT).show()
                            // 通知监听器
                            listener?.onDevicePermissionGranted(it)
                        }
                    } else {
                        Log.d("USB", "权限被拒绝")
                        Toast.makeText(context, "USB设备授权被拒绝", Toast.LENGTH_SHORT).show()
                    }
                }
            }
            UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
                val device = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                device?.let {
                    Log.d("USB", "USB设备已连接: ${it.deviceName}")
                    Toast.makeText(context, "USB设备已连接", Toast.LENGTH_SHORT).show()
                    // 通知监听器
                    listener?.onDeviceAttached(it)
                }
            }
            UsbManager.ACTION_USB_DEVICE_DETACHED -> {
                val device = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                device?.let {
                    Log.d("USB", "USB设备已断开: ${it.deviceName}")
                    Toast.makeText(context, "USB设备已断开", Toast.LENGTH_SHORT).show()
                    // 通知监听器
                    listener?.onDeviceDetached(it)
                }
            }
        }
    }
}